#! /usr/bin/env python
# -*- coding: utf-8 -*-

# Programa principal Table2CSV
# Versão 0.2

import argparse
import sys

from libtable2csv import Table2CSV
from HTMLParser import HTMLParser

class TableParser(HTMLParser):

    table = False
    tr = False
    td_th = False

    def handle_starttag(self, tag, attrs):
        if tag == 'table':
            self.table = True
        if tag == 'tr':
            self.tr = True
        if tag in ['td','th']:
            self.td_th = True

    def is_valid(self):
        return self.table and self.tr and self.td_th

if __name__=="__main__":
    parser = argparse.ArgumentParser(description='Table2CSV Util: converts a HTML table into a CSV file')
    parser.add_argument('inputfile', help='A HTML input file')
    parser.add_argument('outputfile', help='A CSV output file')
    parser.add_argument('--version', '-v', action='version', version='%(prog)s 0.2')
    args = parser.parse_args()

    try:
        input_file = open(args.inputfile).read()
    except IOError as err:
        sys.stderr.write('Error opening file %s: %s\n' % (args.inputfile, err.strerror))
        sys.exit(1)

    parser = TableParser()
    parser.feed(input_file)
    if not parser.is_valid():
        sys.stderr.write("Input File doesn't had a table\n")
        sys.exit(1)

    try:
        output_file = open(args.outputfile, 'w')
    except IOError as err:
        sys.stderr.write('Error opening file %s: %s\n' % (args.outputfile, err.strerror))
        sys.exit(1)

    table2CSV = Table2CSV()
    table2CSV.read(input_file)
    output_file.write(table2CSV.convert().read())
